# 合并购物车函数
import base64
import pickle

from django_redis import get_redis_connection


# 调用的地方，用户登录时，qq登录时。
def merge_cart_function(request,user,response):
    # 解决这个接口我的思维中需要什么？
    # cookie中的数据格式{sku_id{count:count,selected:selected}}
    # 存的时候，哈希存储结构 cart_user_id {sku_id:count} 集合存储结构：cart_selected_user_id {sku_id}
    # 拿cookie中如何操作存到redis中。hset sku_id {sku_id:count}   selected unselected 列表

    # 拿cookie
    cart_cookie = request.COOKIES.get("cart_cookie")
    if not cart_cookie:
        return response
    cart = pickle.loads(base64.b64decode(cart_cookie))
    if not cart:
        return response
    # 存到hash中
    cart = {}
    # 存到set中
    selected_sku_id = []
    unselected_sku_id = []
    for sku_id, value in cart.items():
        cart[sku_id] = value["count"]
        if value["selected"]:
            selected_sku_id.append(sku_id)
        else:
            unselected_sku_id.append(sku_id)
    # 连接redis写入数据
    redis_client = get_redis_connection("cart")
    redis_client.hmset("cart_%s"%user.id,cart)
    if selected_sku_id:
        redis_client.sadd("cart_selected_%s"%user.id,*selected_sku_id)
    if unselected_sku_id:
        redis_client.srem("cart_selected_%s" % user.id, *selected_sku_id)
    response.delete_cookie("cart_cookie")
    return response
